<?php

/**
 * User models
 *
 * User models in bundles
 *
 * PHP Version: 1.2.3
 *
 * @author Johari <joharijumali@gmail.com>
 */

namespace Admin\Models\User;

use \Laravel\Database\Eloquent\Model as Eloquent;
use Laravel\Validator as Validator;
use Datagrid as Datagrid;
use Laravel\Hash as Hash;
use Laravel\Log as Log;
use Laravel\Auth as Auth;
use Admin\Models\User\Profile as Profile;
use Laravel\Str;
use Laravel\Lang;
use Laravel\Config;

/**
 * Data User Model Class
 *
 * Create model class for lookup data
 *
 * @author Johari <joharijumali@gmail.com>
 */

class User extends Eloquent
{

    public static $timestamps = false;
    public static $table = 'sys_user';
    public static $key = 'su_id';

    public static $rules = array(
                                'su_username' => 'required|email', 
                                'su_password' => 'required',
                            );

    /**
     * Function validate that pass parameter
     *
     * @param varchar $data the varchar to quote
	 *
	 * @return parameter.
     */
    public static function validate($data)
	{
        return Validator::make($data, Static::$rules);
    }
	
	/**
     * Function profile
	 *
	 * @return profile.
     */
    public function profile()
    {
        return $this->has_one('Admin\Models\User\Profile', 'su_id');
    }
	
	/**
     * Function roles
	 *
	 * @return roles.
     */
    public function roles()
    {
        return $this->has_one('Admin\Models\User\Role', 'sur_id');
    }
	
	/**
     * Function listUser
	 *
	 * @return listUser.
     */
    public static function listUser()
	{
        $allUser = User::paginate(Config::get('system.pagination'));

        $datagrid = new Datagrid;
        $datagrid->setFields(array('profile/sup_nama' => Str::upper(Lang::line('admin.fullname')->get())));
        $datagrid->setFields(array('profile/sup_emel' => Str::upper(Lang::line('admin.activeemel')->get())));
        $datagrid->setFields(array('profile/sup_no_ic' => Str::upper(Lang::line('admin.idno')->get())));
        $datagrid->setFields(array('su_status' => Str::upper('Status')));
        $datagrid->setAction(Lang::line('global.edit')->get(), 'viewUser', true, array('su_id'));
        $datagrid->setAction(Lang::line('global.delete')->get(), 'deleteAccount', true, array('su_id', 'profile/sup_nama'));
        $datagrid->setAction(Lang::line('global.reset')->get(), 'resetAccount', true, array('su_id'));
        $datagrid->setTable('users', 'table table-bordered table-hover table-striped table-condensed');
        $datagrid->build($allUser, 'su_id');

        return $datagrid->render();
    }
	
	/**
     * Function userSearchList that pass parameter
     *
     * @param varchar $input the varchar to quote
	 *
	 * @return parameter.
     */
    public static function userSearchList($input)
	{
        $operator = (stripos($input['searchval'], '*'))? 'LIKE':'=' ;
        $val = str_replace("*", "", $input['searchval']);
        $refval = (stripos($input['searchval'], '*'))? '%'.$val.'%':$val ;

        $allUser = User::left_join('users_profiles', 'users.userid', '=', 'users_profiles.userid')
                    ->where('icno', $operator, $refval)
                    ->or_where('fullname', $operator, $refval)
                    ->paginate(Config::get('system.pagination'));

        $datagrid = new Datagrid;
        $datagrid->setFields(array('profile/sup_nama' => Str::upper(Lang::line('admin.fullname')->get())));
        $datagrid->setFields(array('profile/sup_emel' => Str::upper(Lang::line('admin.activeemel')->get())));
        $datagrid->setFields(array('profile/sup_no_ic' => Str::upper(Lang::line('admin.idno')->get())));
        $datagrid->setFields(array('su_status' => Str::upper('Status')));
        $datagrid->setAction(Lang::line('global.edit')->get(), 'viewUser', true, array('su_id'));
        $datagrid->setAction(Lang::line('global.delete')->get(), 'deleteAccount', true, array('su_id', 'profile/sup_nama'));
        $datagrid->setAction(Lang::line('global.reset')->get(), 'resetAccount', true, array('su_id'));
        $datagrid->setTable('users', 'table table-bordered table-hover table-striped table-condensed');
        $datagrid->build($allUser, 'su_id');

        return $datagrid->render();
    }
	
	/**
     * Function registerUser that pass parameter
     *
     * @param varchar $input the varchar to quote
	 *
	 * @return parameter.
     */
    public static function registerUser($input)
	{
        $User = new User;
        unset($input['staffno']);
        $id = $User->insert_get_id(array(
			'su_username' => $input['username'],
			'su_password' => Hash::make($input['password']) , 
			'su_validationkey' => $input['key'], 
			'created_at' => date("Y-m-d H:i:s"), 
			'updated_at' => date("Y-m-d H:i:s"), 
			'su_status' => 3, // 1 = active, 2=pendingc confirmation 3=unactive 
			'sur_id' => $input['role']
		));

        unset($input['username']);
        unset($input['password']);
        unset($input['role']);
        unset($input['key']);

        if ($id) {

			// $extension = File::extension($input['imgpath']['name']);
			// $directory = path('public').'avatar/'.sha1($id);
			// $filename = sha1($id.time()).".{$extension}";

			// if($input['imgpath']['size'] != null){

			//     $upload_success = Input::upload('photo', $directory, $filename);

			//     if( $upload_success ) {
			//         $input['imgpath'] = 'avatar/'.sha1($id).'/'.$filename;
			//     }else{
			//         $input['imgpath'] = '';
			//     }
			// }else{
			//     $input['imgpath'] = '';
			// }

            $profile = new Profile(array(
                'sup_nama' => $input['fullname'],
                'sup_no_ic' => $input['icno'],
                'created_at' => date("Y-m-d H:i:s"), 
                'updated_at' => date("Y-m-d H:i:s"),
                'sup_emel' => $input['sup_emel']
            ));

            $user = User::find($id);
            $user->profile()->insert($profile);  

            Log::write('User', 'User '.$input['icno'].' registered');

            return $profile->exists; 

        } else {

            Log::write('User', 'User '.$input['icno'].' failed registered');
            return false;
        }
    }
	
	/**
     * Function userinfo that pass parameter
     *
     * @param integer $id the integer to quote
	 *
	 * @return parameter.
     */
    public static function userinfo($id)
	{
        $userInfo = User::find($id);

        $profile = $userInfo->profile;

        $role = $userInfo->roles;

        $data['username'] = $userInfo->su_username;
        $data['fullname'] = $profile->sup_nama;
        $data['icno'] = $profile->sup_no_ic;
        $data['emel'] = $profile->sup_emel;
        $data['role'] = $userInfo->sur_id;
        $data['status'] = $userInfo->su_status;
        $data['userid'] = $userInfo->su_id;

        return $data;
    }

	/**
     * Function updateUser that pass parameter
     *
     * @param varchar $input the varchar to quote
	 *
	 * @return parameter.
     */
    public static function updateUser($input)
	{
        $user = User::find($input['userid']);
        $profileid = $user->profile->sup_id;
        $user->sur_id = $input['role'];
        $user->su_status = $input['status'];
        $user->save();

        $prof = array(array(
					'sup_nama' => $input['fullname'],
                    'sup_no_ic' => $input['icno'],
                    'sup_emel' => $input['emel'],
                ));

        $profile = Profile::find($profileid);
        $profile->sup_nama = $input['fullname'];
        $profile->sup_no_ic = $input['icno'];
        $profile->sup_emel = $input['emel'];
        $profile->save();

        $profile = User::find($input['userid']);

        Log::write('User', 'Update User '.$user->profile->sup_no_ic.' By <code>'.Auth::user()->username.'</code>');
    }

	/**
     * Function supervisorlist
	 *
	 * @return supervisorlist.
     */
    public static function supervisorlist()
	{

    }

}

?>